///////////////////////////////////////////////////////////////
// File: "CCodeProfiler.cpp"
// Author: James Gonzalez (JG)
// Purpose: Creates timers to check performance of functions
///////////////////////////////////////////////////////////////

#include "CCodeProfiler.h"
#include <stdio.h>
#include <fstream>


CCodeProfiler::CCodeProfiler()
{
	SetAverage(0);
	SetTimeBetween(0);
	SetFunctionName("NotSet");
	m_dTotalHits = 0;
	m_dSum = 0;
	m_bPrintNameOnce = true;
	m_bIsActive = true;
}

void CCodeProfiler::StartTimer(std::string szFunctionName)
{
	if (m_bIsActive)
	{
		m_szFunctionName = szFunctionName;
		QueryPerformanceCounter(&m_liStart); 

	}

}

void CCodeProfiler::EndTimer()
{
	if (m_bIsActive)
	{
		QueryPerformanceCounter(&m_liEnd);
		CalcTimeBetween();
		std::fstream fout;

		fout.open(("CodeProfiler//" + m_szFolder  + "//Function_"+ m_szFunctionName +"().txt").c_str(),std::ios_base::app);
		m_dTotalHits++;
		m_dSum += GetTimeBetween();


		if (fout.is_open())
		{

			if (m_bPrintNameOnce)
			{
				m_bPrintNameOnce = false;
				fout << m_szFunctionName << "\n"; 
			}
			fout << GetTimeBetween() << "\n";
			fout.close();
		} 
	}

}

double CCodeProfiler::CalcAverage()
{
	
	return m_dSum/m_dTotalHits;
}

double CCodeProfiler::CalcTimeBetween()
{
	QueryPerformanceFrequency(&m_liFrequency);
	SetTimeBetween( (double)(m_liEnd.QuadPart - m_liStart.QuadPart) /m_liFrequency.QuadPart );
	return GetTimeBetween();
}
void CCodeProfiler::SetFunctionName(char * szFunctionName)
{
	if (m_bIsActive)
	{
		m_szFunctionName = szFunctionName; 
	}
}

void CCodeProfiler::OutToFile_AVG()
{
	if (m_bIsActive)
	{
		std::fstream fout;
		m_bPrintNameOnce = true;
		fout.open( ("CodeProfiler//"+ m_szFolder +"//All_Averages.txt").c_str(),std::ios_base::app);

		if (fout.is_open())
		{
			fout << m_szFunctionName << "\n";
			fout << m_dTotalHits << " : " << CalcAverage() << "\n";
			fout.close();
		} 
	}
}